package threadtest;


public class VoletileTest {
	private static volatile int a = 0;
	private static volatile int b = 0;

	static boolean locka = true;
	static boolean lockb = true;

	private static long times = 0;
	
	public static void main(String[] args) throws InterruptedException {
		while(true) {
			test();
			if(a != 2) System.out.print("a = " + a + " ");
			if(b != 2) System.out.println("  b = " + b + " ");
			a = 0;
			b = 0;
//			System.out.println("执行了" + times++ + "次");
		}
	}

	private static void test() throws InterruptedException {
		locka = true;
		lockb = true;
		TA TA = new TA();
		TB TB = new TB();
		TA.start();
		TB.start();
		TA = null;
		TB = null;
		wait_util_TA_TB_over_(); // 等到TA, TB终止
	}

	private static void wait_util_TA_TB_over_() throws InterruptedException {
		
		//如果有1个锁没有开, 那么就继续等待...(如果TA,TB两个线程有一个线程没有执行完, 那么就继续等待)
		if(locka || lockb) {	
			System.gc();
			wait_util_TA_TB_over_();
		}
	}

	private static class TA extends Thread {
		@Override
		public void run() {
			a++;
			b++;
		}
		
		@Override
		protected void finalize() throws Throwable {
			locka = false;
		}
	}

	private static class TB extends Thread {
		@Override
		public void run() {
			a++;
			b++;
		}
		
		@Override
		protected void finalize() throws Throwable {
			lockb = false;
		}
	}
}
